package com.jia.leetCode;

/**
 * @program: Leetcode
 * @description:
 * @author: STU756
 * @create: 2020-08-13 00:20
 */

/**
 * 43. 字符串相乘
 */
public class Pro0043 {
    public String multiply2(String num1, String num2) {
        if (num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0 || num1.equals("0")
                || num2.equals("0")) {
            return "0";
        }
        int n1 = num1.length();
        int n2 = num2.length();
        int len = n1 + n2;
        int[] rst = new int[len];
        for (int i = n1 - 1; i > -1; i--) {
            int d = num1.charAt(i) - '0';
            for (int j = n2 - 1; j > -1; j--) {
                int carry = d * (num2.charAt(j) - '0') + rst[i + j + 1];
                rst[i + j + 1] = carry % 10;
                rst[i + j] += carry / 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        int k = rst[0] == 0 ? 1 : 0;
        for (; k < len; k++) {
            sb.append(rst[k]);
        }
        return sb.toString();
    }
    public String multiply(String num1, String num2) {
        if (num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0 || num1.equals("0")
                || num2.equals("0")) {
            return "0";
        }
        int len1 = num1.length();
        int len2 = num2.length();
        int[] res = new int[len1 + len2];
        int index = res.length -1;
        int carry = 0;
        for(int i = len1 - 1; i >=  0; i --) {
            int n1 = num1.charAt(i) - '0';
            carry = 0;
            for(int j = len2 - 1; j >=0; j --) {
                int n2 = num2.charAt(j) - '0';
                int temp = res[i + j + 1];
                res[i + j + 1] = (n1 * n2 + res[i+j+1] + carry) % 10;
                res[i+j] += (temp + n1 * n2) / 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while(i < res.length && res[i] == 0)i++;
        for(;i<res.length; i++) {
            sb.append(res[i]);
        }
        return sb.toString();
    }
}
